package database

import (
	"fmt"
	"net/url"

	"github.com/quixote-liu/config"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func InitMysqlDatabase() (*DatabaseService, error) {
	opts := mysqlOpts()

	var err error
	db, err = gorm.Open(mysql.Open(opts.dsn()), &gorm.Config{})
	if err != nil {
		return nil, fmt.Errorf("connect mysql database failed: %v", err)
	}

	return &DatabaseService{db: db}, nil
}

type mysqlOptions struct {
	username string
	password string
	port     string
	host     string
	dbname   string
}

func (opts mysqlOptions) dsn() string {
	return fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?"+opts.dsnParams(),
		opts.username, opts.password, opts.host, opts.port, opts.dbname)
}

func (opts mysqlOptions) dsnParams() string {
	v := url.Values{}
	// support time.Time.
	v.Set("parseTime", "true")
	v.Set("loc", "Local")

	// set read, write and connection timeout.
	v.Set("readTimeout", "10s")
	v.Set("timeout", "10s")
	v.Set("writeTimeout", "10s")
	return v.Encode()
}

func mysqlOpts() mysqlOptions {
	conf := config.CONF()
	group := "mysql"
	return mysqlOptions{
		username: conf.GetString(group, "user_name"),
		password: conf.GetString(group, "password"),
		port:     conf.GetString(group, "port"),
		host:     conf.GetString(group, "host"),
		dbname:   conf.GetString(group, "dbname"),
	}
}
